<?php
require './function.php';
/**
 * @Author: Wherein
 * @Date: 2021-03-25 09:51
 * @Descripttion: 适配器模式
 * @example cache 缓存选择, DB 选择
 */

interface Target
{
    public function connect($host, $user, $password, $dbname);
    public function query($sql);
    public function close();
}

class PdoAdaptee implements Target
{
    protected $conn;

    public function connect($host, $user, $password, $dbname)
    {
        $conn =  new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
        $this->conn = $conn;
    }
    public function query($sql)
    {
        $res = $this->conn->query($sql);
        return $res;
    }
    public function close()
    {
        $this->conn = null;
    }
}

class MySQLiAdaptee implements Target
{
    protected $conn;

    public function connect($host, $user, $password, $dbname)
    {
        $conn =  mysqli_connect($host, $user, $password, $dbname);
        $this->conn = $conn;
    }
    public function query($sql)
    {
        $res = mysqli_query($this->conn, $sql);
        return $res;
    }
    public function close()
    {
        mysqli_close($this->conn);
    }
}

class DataBase implements Target
{
    protected $db;
    public function __construct($type)
    {
        $type = $type . 'Adaptee';
        $this->db = new $type;
    }
    public function connect($host, $user, $password, $dbname)
    {
        $this->db->connect($host, $user, $password, $dbname);
    }
    public function query($sql)
    {
        return $this->db->query($sql);
    }

    public function close()
    {
        $this->db->close();
    }
}

// 测试
$db1 = new DataBase('MySQLi');
$db1->connect('127.0.0.1', 'root', 'root', 'learn_test');
$list = $db1->query('select * from `hero`');
dd($list);
$db1->close();

